//
//  NSData+Extension.m
//  MiGuPlay
//
//  Created by Migu on 16/9/8.
//  Copyright © 2016年 Migu. All rights reserved.
//

#import "NSData+Extension.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NSData(Extension)

- (NSData *)AESEncryptWithKey:(NSString *)key iv:(NSString *)iv {
    return [self AESOperation:kCCEncrypt key:key iv:iv];
}

- (NSData *)AESDecryptWithKey:(NSString *)key iv:(NSString *)iv {
    return [self AESOperation:kCCDecrypt key:key iv:iv];
}


- (NSData *)AESOperation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv {
    // KEY
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    // IV
    char ivPtr[kCCBlockSizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    size_t bufferSize = [self length] + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    
    CCCryptorStatus cryptorStatus = CCCrypt(operation, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES128, ivPtr, [self bytes], [self length], buffer, bufferSize, &numBytesEncrypted);
    if (cryptorStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}

@end
